Obsidian で現在開いているファイル位置までスクロールするスクリプト

作成日
更新日

Obsidian で現在開いているファイル位置までスクロールするスクリプトをCustomJSで追加。

  • 設定よりホットキーを追加する
  • Xcodeと同様にcmd + shift + j で移動する。

cusomjs_set_hotkey

コード

ファイルの実態は 001_Config/src/scrollToCurrentFile.jsに保存。

class ScrollToCurrentFile {
  async invoke() {
    try {
      const currentFile = app.workspace.getActiveFile();
      if (!currentFile) {
        new Notice("No active file found.", 5000);
        return;
      }

      const filePath = currentFile.path;
      const explorerLeaf = app.workspace.getLeavesOfType("file-explorer")[0];
      if (explorerLeaf) {
        // まずエクスプローラーをリセット(必要に応じて設定)
        explorerLeaf.view.revealInFolder(currentFile);

        // 少し時間を待つ(スクロールリセットが完了するのを待つ)
        await new Promise(resolve => setTimeout(resolve, 300));

        const fileEl = explorerLeaf.view.containerEl.querySelector(`[data-path="${filePath}"]`);
        if (fileEl) {
          // 少し上までスクロールするための調整
          const additionalScroll = 50; // 必要に応じて調整
          fileEl.scrollIntoView({ behavior: "smooth", block: "center" });
          explorerLeaf.view.containerEl.scrollTop -= additionalScroll;

          fileEl.classList.add("is-active");
          const fileName = currentFile.name;
          new Notice(`「${fileName}」ファイルへ移動`, 5000);
        } else {
          new Notice("File not found in the explorer.", 5000);
        }
      } else {
        new Notice("File Explorer not found.", 5000);
      }
    } catch (error) {
      new Notice("Error occurred: " + error.message, 5000);
      console.error(error);
    }
  }
}
サイトアイコン
公開日
更新日